#include "callbackMem.h"

#define MAX_SIZE 256

typedef struct __callbackEntry{
	unsigned int id;
	pf_notificacion_echo function;
} CALLBACK_ENTRY;

typedef struct __callbackMem{
	CALLBACK_ENTRY notifyArray[MAX_SIZE];
	int last;
} HOLA;

CALLBACK_MEM createCallbackMem()
{
	CALLBACK_MEM callMem=NULL;
	
	callMem=(struct __callbackMem *) calloc(1, sizeof(struct __callbackMem));
	if(callMem==NULL){
		return NULL;
	}
	
	callMem->last=0;
	
	return callMem;
}

void freeCallbackMem(CALLBACK_MEM callMem)
{
	free(callMem);
	
	return;
}

CALLBACK_MEM_ERRCODE registerCallback(CALLBACK_MEM callMem, unsigned int id, pf_notificacion_echo function)
{
	if(callMem==NULL){
		return CALLBACK_MEM_ERR;
	}
	
	if(callMem->last==(MAX_SIZE-1)){
		return CALLBACK_MEM_FULL;
	}
	
	if(findCallback(callMem, id)>=0){
		return CALLBACK_MEM_OK;
	}
	
	callMem->notifyArray[callMem->last].id=id;
	callMem->notifyArray[callMem->last].function=function;
	callMem->last++;
	
	return CALLBACK_MEM_OK;
}

pf_notificacion_echo getCallback(CALLBACK_MEM callMem, unsigned int id)
{
	int entryIndex=0;
	
	if(callMem==NULL){
		return NULL;
	}
	
	//printf("GET ECHO CALLBACK: callMem->last=%d", callMem->last);
	
	entryIndex=findCallback(callMem, id);
	//printf("GET ECHO CALLBACK: Entrada=%d\n", entryIndex);
	if(entryIndex<0){
		return NULL;
	}
	
	return callMem->notifyArray[entryIndex].function;
}

int findCallback(CALLBACK_MEM callMem, unsigned int id)
{
	int i;
	short found=0;
	
	if(callMem==NULL){
		return -1;
	}
	
	for(i=0; i<callMem->last && !found; i++){
		//printf("FINDCALLBACK: notifyArray[%d].id=%d - buscando=%d", i, callMem->notifyArray[i].id, id );
		if(callMem->notifyArray[i].id==id){
			found=1;
		}
	}
	
	if(found){
		return i-1;
	}
	
	return -1;
}

